//
//  NSArray+XHLKit.m
//  XHLKit
//
//  Created by qinyulun on 16/6/17.
//  Copyright © 2016年 leTian. All rights reserved.
//

#import "NSArray+XHLKit.h"

@implementation NSArray (XHLKit)

- (id)safeObjectAtIndex:(NSUInteger)index {
    if ([self count] > index)
        return [self objectAtIndex:index];
    else
        return nil;
}

- (NSArray *)reversedArray {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
    NSEnumerator *enumerator = [self reverseObjectEnumerator];
    
    for (id element in enumerator)
        [array addObject:element];
    
    return array;
}

- (NSString *)arrayToJson {
    NSString *json = nil;
    NSError *error = nil;
    NSData *data =
    [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
    if (!error) {
        json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        return json;
    } else{
       return nil;
    }
}

+ (NSArray *)arrWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:NSJSONReadingMutableContainers
                                                     error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return arr;
}

@end
